<template>
  <zlst-ele-layout class="card-list">
    <!-- 头部 -->
    <div slot="zlst-ele-header__search">
      <h3 class="title"><span>卡片管理</span></h3>
      <el-button class="operate-button" type="primary" icon="el-icon-plus" @click="showDialog('1')">新增容器</el-button>
      <el-button class="operate-button" type="primary" icon="el-icon-plus" @click="showDialog('2')">新增卡片</el-button>
    </div>
    <div slot="zlst-ele-header__filter">

      <el-button class="operate-button" style="float: right;position: relative; top: 2px;margin-left: 10px" type="primary" @click="query(true)">搜索</el-button>

      <el-input v-model.trim="queryObj.cardName" class="search-input w-150" placeholder="请输入分组名称" />
      <div class="group">
        <div class="label">分组</div>
        <el-select v-model="queryObj.groupNo" filterable clearable class="w-150" placeholder="请选择分组" @change="query(true)">
          <el-option v-for="item in groupOptions" :key="item.value" :label="item.groupName" :value="item.groupNo" />

        </el-select>
      </div>
      <div class="group">
        <div class="label">卡片类型</div>
        <el-select v-model="queryObj.cardCategory" clearable class="w-150" placeholder="请选择卡片类型" @change="query(true)">
          <el-option v-for="item in cardTypeOptions" :key="item.value" :label="item.label" :value="item.value" />

        </el-select>
      </div>
      <div class="group">
        <div class="label">状态</div>
        <el-select v-model="queryObj.active" clearable class="w-150" placeholder="请选择状态" @change="query(true)">
          <el-option v-for="item in activeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div class="group">
        <div class="label">权限</div>
        <el-select v-model="queryObj.authorityFlag" clearable class="w-150" placeholder="请选择权限" @change="query(true)">
          <el-option v-for="item in authorityFlagOptions" :key="item.value" :label="item.label" :value="item.value" />

        </el-select>
      </div>

    </div>
    <div slot="zlst-ele-container__main__content">
      <el-dialog
        title="编辑容器"
        :visible.sync="linkShow"
        width="60%"
        @closed="closed"
      >
        <div class="content">
          <div class="aside">
            <div class="head">
              <el-input
                v-model="filterText"
                style="width: 60%; margin-right: 10px"
                placeholder="输入关键字进行过滤"
              />
              <el-button type="primary" @click="clearIframeCard">新增</el-button>
            </div>
            <div class="tree-wrapper">
              <el-tree ref="tree" :expand-on-click-node="false" default-expand-all highlight-current node-key="id" :filter-node-method="filterNode" :data="treeData" @node-click="handleNodeClick">
                <span slot-scope="{ node, data }" class="custom-tree-node">
                  <span class="text">{{ data.name }}</span>
                  <span style="float: right">
                    <i
                      class="el-icon-circle-plus-outline"
                      style="margin-right: 5px"
                      @click.stop="() => append(data)"
                    />
                    <i
                      class="el-icon-remove-outline"
                      size="mini"
                      @click.stop="() => remove(data)"
                    />
                  </span>
                </span>
              </el-tree>
            </div>
          </div>
          <div class="main">
            <el-select v-model="iframeCardId" :disabled="!parentId" filterable placeholder="请选择卡片" style="margin-top: 50px">
              <el-option v-for="item in iframeList" :key="item.cardId" :label="item.cardName" :value="item.cardId" />
            </el-select>
            <div class="bottom">
              <el-button type="primary" @click="addNode">确定</el-button>
            </div>
          </div>
        </div>

      </el-dialog>
      <el-dialog
        :title="title"
        :visible.sync="dialogShow"
        width="30%"
      >
        <el-form ref="cardForm" :rules="rules" :model="form" label-position="top">
          <el-form-item v-if="type === 'edit'" prop="groupName" label="卡片编号">
            <el-input v-model="form.groupName" disabled placeholder="请输入分组名称" />
          </el-form-item>
          <el-form-item prop="cardName" label="卡片名称" required>
            <el-input v-model="form.cardName" placeholder="请输入卡片名称" />
          </el-form-item>
          <el-form-item prop="cardLength" label="卡片高度（30px倍数）" required>
            <el-input-number v-model.number="form.cardLength" :min="1" placeholder="请输入卡片高度" />
          </el-form-item>
          <el-form-item prop="cardWidth" label="卡片宽度（12格栅）" required>
            <el-input-number v-model.number="form.cardWidth" :min="1" :max="12" placeholder="请输入描述" />
          </el-form-item>
          <el-form-item prop="groupNo" label="卡片分组" required>
            <el-select v-model="form.groupNo" filterable clearable placeholder="请选择分组">
              <el-option v-for="item in groupOptions" :key="item.value" :label="item.groupName" :value="item.groupNo" />

            </el-select>
          </el-form-item>
          <el-form-item prop="cardCategory" label="卡片分类" required>
            <el-select v-model="form.cardCategory" disabled clearable placeholder="请选择卡片类型">
              <el-option v-for="item in cardTypeOptions" :key="item.value" :label="item.label" :value="item.value" />

            </el-select>
          </el-form-item>
          <el-form-item prop="authorityFlag" label="权限管理" required>
            <el-select v-model="form.authorityFlag" clearable placeholder="请选择权限">
              <el-option v-for="item in authorityFlagOptions" :key="item.value" :label="item.label" :value="item.value" />

            </el-select>
          </el-form-item>
          <el-form-item v-if="form.cardCategory === '2'" prop="cardUrl" label="卡片链接">
            <el-input v-model="form.cardUrl" placeholder="请输入卡片链接" />
          </el-form-item>
          <el-form-item v-if="form.cardCategory === '1'" prop="publishFlag" label="发布到移动端">
            <el-switch
              v-model="form.publishFlag"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="reset">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </el-dialog>
      <el-table
        ref="table"
        v-loading="listLoading"
        :data="cardList"
      >
        <el-table-column label="编号" type="index" />
        <el-table-column show-overflow-tooltip label="卡片名称" prop="cardName" />
        <el-table-column show-overflow-tooltip label="分组" prop="groupName" />
        <el-table-column label="卡片分类">
          <template slot-scope="{row}">
            {{ row.cardCategory | filterType }}
          </template>
        </el-table-column>
        <el-table-column label="最小尺寸" prop="groupName">
          <template slot-scope="{row}">
            {{ `${row.cardWidth},${row.cardLength}` }}
          </template>
        </el-table-column>
        <el-table-column label="权限管理">
          <template slot-scope="{row}">
            <span v-show="row.authorityFlag === '1'">公开</span>
            <el-button v-show="row.authorityFlag === '2'" type="text" @click="auth(row)">私有</el-button>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="active">
          <template slot-scope="{row}">
            {{ row.active === '0' ? '启用' : '禁用' }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200">
          <template slot-scope="{row}">
            <el-button type="text" @click="update(row.cardId, row.active)">{{ row.active === '0' ? '禁用' : '启用' }}</el-button>
            <el-button type="text" @click="showDialog('edit',row)">编辑</el-button>
            <el-button v-if="row.cardCategory === '1'" type="text" @click="linkCardOop(row)">关联卡片</el-button>
          </template>
        </el-table-column>

      </el-table>
      <userInfo ref="info" :dialog-show="infoShow" title="拥有权限" @signOut="signOut" @uploadDispatchPost="uploadDispatchPost" />
    </div>
    <template slot="zlst-ele-footer">
      <el-pagination
        :current-page.sync="queryObj.currPage"
        :page-sizes="[10, 20, 40, 60, 80]"
        :page-size.sync="queryObj.pageSize"
        layout="sizes, prev, pager, next"
        :total="total"
        @size-change="query"
        @current-change="query"
      />
    </template>

  </zlst-ele-layout>
</template>

<script>
import { getCardList, getCardInfo, getAuthCard, addCard, updateCardCondition, authCard, editCard, deleteContainerNode, getContainerTree, getContainerCard, saveContainerCard, updateContainerCard } from '@/api/server/card'
import { getGroups } from '@/api/server/groups'
import { cloneDeep } from 'lodash'
import userInfo from './userInfo'

export default {
  components: {
    userInfo
  },
  filters: {
    filterType(type) {
      const map = {
        '1': '容器',
        '2': '嵌套',
        '3': '应用跳转',
        '4': '图形',
        '5': '菜单跳转',
        '6': '历史应用',
        '7': '表格'
      }
      return map[type]
    }
  },
  props: {

  },
  data() {
    return {
      queryObj: {
        authorityFlag: '',
        cardName: '',
        active: '',
        groupNo: '',
        cardType: '',
        pageSize: 20,
        currPage: 1
      },
      total: 0,
      activeOptions: [
        { label: '启用', value: '0' },
        { label: '禁用', value: '1' }
      ],
      authorityFlagOptions: [
        { label: '公开', value: '1' },
        { label: '私有', value: '2' }
      ],
      cardTypeOptions: [
        { label: '容器', value: '1' },
        { label: '嵌套', value: '2' },
        { label: '应用跳转', value: '3' },
        { label: '图形', value: '4' },
        { label: '菜单跳转', value: '5' },
        { label: '历史应用', value: '6' },
        { label: '表格', value: '7' }
      ],
      infoShow: false,
      dialogLoading: false,
      groupOptions: [],
      rules: {
        cardName: [{ required: true, message: '请输入卡片名称', trigger: ['blur', 'change'] }],
        cardLength: [{ required: true, message: '请输入卡片高度', trigger: ['blur', 'change'] }],
        cardWidth: [{ required: true, message: '请输入卡片宽度', trigger: ['blur', 'change'] }],
        groupNo: [{ required: true, message: '请选择分组', trigger: ['blur', 'change'] }],
        cardCategory: [{ required: true, message: '请选择卡片分类', trigger: ['blur', 'change'] }],
        authorityFlag: [{ required: true, message: '请输选择卡片权限', trigger: ['blur', 'change'] }]
      },
      form: {},
      title: '',
      dialogShow: false,
      cardList: [],
      listLoading: false,
      type: '',
      currentAuthCard: {},
      treeData: [],
      filterText: '',
      cardId: '',
      iframeList: [],
      iframeCardId: '',
      linkShow: false,
      parentId: '',
      nodeId: ''
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    this.query()
    this.getGroups()
  },
  methods: {
    linkCardOop({ cardId }) {
      this.linkShow = true
      this.linkCard({ cardId })
      this.getIframs()
    },
    clearIframeCard() {
      this.parentId = '0'
      this.iframeCardId = ''
      this.getIframs()
    },
    closed() {
      this.iframeCardId = ''
      this.parentId = ''
      this.nodeId = ''
      this.cardId = ''
      this.treeData = []
    },
    async getIframs() {
      try {
        this.iframeList = (await getCardList({
          currPage: 1,
          pageSize: 20000,
          cardCategory: '2'
        })).data.list
      } catch (e) {
        console.log(e)
      }
    },
    async addNode() {
      try {
        if (this.nodeId) {
          const node = {
            id: this.nodeId,
            cardContainerId: this.iframeCardId
          }
          await updateContainerCard(node)
        } else {
          const node = {
            cardId: this.cardId,
            parentId: this.parentId,
            cardContainerId: this.iframeCardId
          }
          await saveContainerCard(node)
        }
        this.$message.success('操作成功！')
        this.linkCard({ cardId: this.cardId })
      } catch (e) {
        console.log(e)
      }
    },
    handleNodeClick(data) {
      this.parentId = data.parentId
      this.nodeId = data.id
      this.iframeCardId = data.cardContainerId
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    async linkCard({ cardId }) {
      try {
        this.cardId = cardId || this.cardId
        this.treeLoading = true
        this.treeData = (await getContainerTree({
          cardId
        })).data
      } catch (e) {
        console.log(e)
      } finally {
        this.treeLoading = false
      }
    },
    async getGroups() {
      try {
        const res = (await getGroups({
          currPage: 1,
          pageSize: 20000,
          searchValue: ''
        })).data
        this.groupOptions = res.list
      } catch (e) {
        console.log(e)
      } finally {
        this.listLoading = false
      }
    },
    async uploadDispatchPost(list) {
      try {
        await authCard({
          authorityFlag: this.currentAuthCard.authorityFlag,
          cardId: this.currentAuthCard.cardId,
          userIds: list.map(v => v.userId)
        })
        this.$message.success('授权成功！')
        this.infoShow = false
        this.query()
      } catch (e) {
        console.log(e)
      }
    },
    signOut() {
      this.infoShow = false
    },
    async auth(row) {
      try {
        this.currentAuthCard = row
        this.$refs.info.checkUserList(row.cardInfoUserVOs ? row.cardInfoUserVOs : [])
        this.infoShow = true
      } catch (e) {
        console.log(e)
      }
    },
    append(data) {
      this.parentId = data.id
      this.$refs.tree.setCurrentKey('')
      this.iframeCardId = ''
      this.nodeId = ''
    },
    async remove(data) {
      try {
        await this.$confirm('是否要删除该节点？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteContainerNode(data.id)
        this.$message.success('操作成功！')
        this.linkCard({ cardId: this.cardId })
      } catch (e) {
        console.log(e)
      }
    },
    showDialog(type, payload) {
      this.type = type
      if (this.type === 'edit') {
        this.form = cloneDeep(payload)
        this.title = '编辑卡片'
      } else {
        this.form = {
          cardCategory: type
        }
        this.form.active = '0'
        this.title = '新增卡片'
      }
      if (this.cardCategory === '1') {
        this.form.publishFlag = this.form.publishFlag !== '0'
      }
      this.dialogShow = true
      this.$nextTick(() => {
        this.$refs.cardForm && this.$refs.cardForm.clearValidate()
      })
    },
    async query(init) {
      try {
        this.listLoading = true
        if (init) {
          this.queryObj.pageSize = 20
          this.queryObj.currPage = 1
        }
        const res = (await getCardList(this.queryObj)).data
        this.total = res.totalCount
        this.cardList = res.list
      } catch (e) {
        console.log(e)
      } finally {
        this.listLoading = false
      }
    },
    async update(cardId, active) {
      try {
        if (active === '0') {
          await this.$confirm('禁用该卡片，用户无法使用该卡片', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        }
        await updateCardCondition({
          cardId,
          active: active === '0' ? '1' : '0'
        })
        this.$message.success('操作成功！')
        this.query(true)
      } catch (e) {
        console.log(e)
      }
    },
    async save() {
      try {
        this.dialogLoading = true
        if (this.form.cardCategory === '1') {
          this.form.publishFlag = this.form.publishFlag ? '1' : '0'
        }
        if (this.type === 'edit') {
          await editCard(this.form)
        } else {
          await addCard(this.form)
        }
        this.$message.success('修改成功')
        this.dialogShow = false
        this.query()
      } catch (e) {
        console.log(e)
      } finally {
        this.dialogLoading = false
      }
    },
    reset() {
      this.dialogShow = false
      this.$refs.cardForm && this.$refs.cardForm.resetFields()
      this.form = {}
    }
  }
}
</script>

<style scoped lang="scss">
  .w-150 {
    width: 150px;
  }
  .search-input {
    float: right;
  }
  .group {
    float: right;
    margin-right: 10px;
    display: inline-block;
    .label {
      display: inline;
      font-size: 14px;
      color: #999;
      margin-right: 10px;
    }
  }
  .content {
    width: 100%;
    height: 400px;
    display: flex;
    flex-wrap: nowrap;
    .aside {
      width: 200px;
      margin-right: 20px;
      padding-top: 10px;
      .tree-wrapper {
        height: calc(100% - 42px);
        margin-top: 10px;
        overflow: auto;
      }

    }
    .main {
      width: calc(100% - 220px);
      height: 100%;
      text-align: center;
      position: relative;
      border: 1px solid #999;

      .bottom {
        position: absolute;
        right: 20px;
        bottom: 10px;
      }
    }
  }
  .custom-tree-node {
    width: 100%;
    .text {
      width: calc(100% - 35px);
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
  }
</style>
